package sg.edu.nus.iss.jass.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;

import sg.edu.nus.iss.jass.gui.JASSWindow;
import sg.edu.nus.iss.jass.gui.LoginWindow;
import sg.edu.nus.iss.jass.gui.ToolbarMenu;
import sg.edu.nus.iss.jass.model.CurrentUserDTO;

/**
 * @version 1.0
 * @author SE19 Team 1
 * 
 */
public class MainMenuController implements ActionListener {

	private CurrentUserDTO currentUserDTO;
	private LoginWindow loginWindow;
	private JASSWindow jassWindow;

	// Handle the top menu actions
	public void actionPerformed(ActionEvent e) {
		String button = ((JComponent)e.getSource()).getName();
		
		if (ToolbarMenu.BTN_ADD_JOBADVERT.equals(button)) {
			JobAdvertController jobAdvertController = new JobAdvertController(this);
			jobAdvertController.initAddJobAdvertScreen(this.currentUserDTO.getUserId());
		} 
		else if (ToolbarMenu.BTN_SEARCH_JOBADVERT.equals(button)) {
			JobAdvertController jobAdvertController = new JobAdvertController(this);
			jobAdvertController.initSearchJobAdvertScreen(this.currentUserDTO.getUserId());
		} 
		else if (ToolbarMenu.BTN_RESPONSE.equals(button)) {
			ResponseController responseController = new ResponseController(this);
			responseController.initViewResponseListScreen(this.currentUserDTO);
		} 
		else if (ToolbarMenu.BTN_LOGOUT.equals(button)) {
			displayLoginPage();
		}
	}

	// display the main window
	public void displayMainMenu() {
		if (jassWindow != null && jassWindow.isShowing()) {
			jassWindow.dispose();
		}
		loginWindow.setVisible(false);
		jassWindow = new JASSWindow(this);
	}

	// after log out, switch to login window from main window and clear the
	// session
	public void displayLoginPage() {
		if (jassWindow != null && jassWindow.isShowing()) {
			jassWindow.dispose();
		}
		
		if(loginWindow == null){
			loginWindow = new LoginWindow(this);
		}
		loginWindow.setVisible(true);
		
		currentUserDTO = null;
	}

	// switch the current display panel
	public void switchPage(JComponent component) {
		jassWindow.switchPage(component);
	}

	// sets the current user's session
	public void setCurrentUser(String sessionId, String userId) {
		currentUserDTO = new CurrentUserDTO(sessionId, userId);
	}

	// reads the session to determine the currently logged on user
	public CurrentUserDTO getCurrentUser() {
		return currentUserDTO;
	}

	// quits the program
	public void exitProgram() {
		System.exit(0);
	}
}
